#ifndef MQTTMSGPARSE_HPP
#define MQTTMSGPARSE_HPP

#include <iostream>
#include <vector>

#include <json.hpp>
#include <MqttCommon.hpp>
#include <Config.hpp>

using namespace std::chrono_literals;
using namespace std::chrono;

class MqttMsgParse {
public:
	MqttMsgParse(std::shared_ptr<AppConfig> config) 
		: config_(config) {
		// try {

		// } catch (const YAML::Exception& e) {
		// 	// 捕获 YAML 异常，并进行错误处理
		// 	std::cerr << "YAML parsing error: " << std::endl;

		// }
	}

	~MqttMsgParse() = default;

	/* 处理消息队列 */
	bool parseMsg(const Msg& msg) {
		std::cout << msg << std::endl;
        if ( msg.topic.find("sys_manager") != std::string::npos
            || msg.topic.find("rack") != std::string::npos
            || msg.topic.find("wack") != std::string::npos
            || msg.topic.find("info") != std::string::npos) {
            return deviceReplyMsgParse(msg);				/* 本地消息处理 */
        } else {
            return true;
        }
		return true;
	}
private:
	/* write回复消息 TODO */
	bool writeReplyProcess(const Msg& msg) {
		//LOG_DEBUG("infoReplyProcess");
		return true;
	}

	/* read回复消息 */
	bool readReplyProcess(const Msg& msg) {
		//LOG_DEBUG("readReplyProcess");
		nlohmann::json json = nlohmann::json::parse(msg.payload);
		const std::string& name = json.at("src");
		for (auto& app : config_->appList) {
			if (app.name == name) {
				app.status = 1;
				if (json.count("app") && json.at("app").count("points")) {
					const auto& points = json.at("app").at("points");
					for (const auto & point : points) {
						if (point.count("key")) {
							std::string key = point.at("key").get<std::string>();
							std::string val = point.at("val").get<std::string>();
							if (key == "log") {
								app.log = val;
								//LOG_DEBUG("log: {}", app.log.c_str());
							} else if (key == "version") {
								app.version = val;
								//LOG_DEBUG("version: {}", app.version.c_str());
							} else if (key == "date") {
								app.date = val;
								//LOG_DEBUG("date: {}", app.date.c_str());
							}
						}
					}
				}
			}
		}

		return true;
	}

	/* info回复消息 TODO */
	bool infoReplyProcess(const Msg& msg) {
		//LOG_DEBUG("infoReplyProcess");
		return true;
	}

	/* 回复消息处理 */
	bool deviceReplyMsgParse(const Msg& msg) {
		//LOG_DEBUG("deviceReplyMsgParse");
		if (msg.topic.find("/0/info") != std::string::npos) {
			return infoReplyProcess(msg);
		} else if (msg.topic.find("rack") != std::string::npos) {
			return readReplyProcess(msg);
		} else if (msg.topic.find("wack") != std::string::npos) {
			return writeReplyProcess(msg);
		} else {
			return false;
		}
	}

private:
	std::shared_ptr<AppConfig> config_;
};


#endif //MQTTMSGPARSE_HPP
